package com.runshu.newsmartark.activity;

import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.runshu.newsmartark.R;
import com.runshu.newsmartark.adapter.TakeStockAdapter;
import com.runshu.newsmartark.base.MyApplication;
import com.runshu.newsmartark.dbutil.DBUtils;
import com.runshu.newsmartark.dbutil.ProAllEntity;
import com.runshu.newsmartark.dbutil.RefreshUtils;
import com.runshu.newsmartark.entity.CategoryListEntity;
import com.runshu.newsmartark.entity.ConfirmStockEntity;
import com.runshu.newsmartark.entity.InventoryEPCBean;
import com.runshu.newsmartark.entity.NewTakeStockEntity;
import com.runshu.newsmartark.entity.ProductsBean;
import com.runshu.newsmartark.mvp.contract.ConfirmStockContract;
import com.runshu.newsmartark.mvp.contract.ProductTypeDtaContract;
import com.runshu.newsmartark.mvp.contract.ProductsByCategoryContract;
import com.runshu.newsmartark.mvp.model.ConfirmStockModel;
import com.runshu.newsmartark.mvp.model.ProductTypeDtaModel;
import com.runshu.newsmartark.mvp.model.ProductsByCategoryModel;
import com.runshu.newsmartark.mvp.presenter.ConfirmStockPresenter;
import com.runshu.newsmartark.mvp.presenter.ProductTypeDtaPresenter;
import com.runshu.newsmartark.mvp.presenter.ProductsByCategoryPresenter;
import com.runshu.newsmartark.network.netbean.ResponseBean;
import com.runshu.newsmartark.reader.base.TakeStockBase;
import com.runshu.newsmartark.reader.helper.InventoryBuffer;
import com.runshu.newsmartark.util.Beeper;
import com.runshu.newsmartark.util.MTagRealList;
import com.runshu.newsmartark.util.MacUtils;
import com.runshu.newsmartark.util.RecyclerViewNoBugLinearLayoutManager;
import com.runshu.newsmartark.util.SoundPoolUtils;
import com.runshu.newsmartark.util.common.LogUtil;
import com.runshu.newsmartark.util.common.SharedPreferencesUtils;
import com.runshu.newsmartark.util.common.ToastUtils;
import com.runshu.newsmartark.util.widget.CommonShowDialog;
import com.runshu.newsmartark.util.widget.TopTitleBar;
import com.zxl.library.DropDownMenu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

import static com.runshu.newsmartark.common.ConstantUrl.Share_Category;

/**
 * Demo class
 *
 * @author yu
 * @date 2020/8/26
 * @decs：
 */

public class TakeStockDtaActivity extends TakeStockBase implements ProductsByCategoryContract.View, ConfirmStockContract.View, ProductTypeDtaContract.View {
    private static final String TAG = "TakeStockDtaActivity";
    @BindView(R.id.toolbar)
    TopTitleBar mToolbar;
    @BindView(R.id.tv_all_num)
    TextView mTvAllNum;
    @BindView(R.id.rela_root)
    RelativeLayout mRelaRoot;
    @BindView(R.id.dropDownMenu)
    DropDownMenu mDropDownMenu;
    private List<ProductsBean> mData;
    private TakeStockAdapter mAdapter;
    private ProductsByCategoryPresenter productsPresenter;
    private ConfirmStockPresenter confirmStockPresenter;
    private ProductTypeDtaPresenter typeDtaPresenter;
    private CommonShowDialog commonShowDialog;
    private boolean isCloseDoor = true;
    private MTagRealList mTagRealList;
    //标识重新盘点用
    private String type;
    private List<CategoryListEntity> categoryList;
    private List<CategoryListEntity> ManufacturerSelList;
    private List<CategoryListEntity> ModelSelList;

    private boolean isLoadMore = false;
    private int pageSize = 10;
    private int pageNum = 1;
    private String categoryValue, stockName, model, manufacturer;
    private String macAddress;
    private String headers[] = {"产品类别", "产品规格", "生产厂家"};
    private String selectTypeOne[] = {};
    private String selectTypeTwo[] = {};
    private String selectTypeThree[] = {};
    private int[] types = new int[]{DropDownMenu.TYPE_LIST_CITY, DropDownMenu.TYPE_LIST_CITY, DropDownMenu.TYPE_LIST_CITY};
    private SwipeRefreshLayout mSwipeLayout;
    private RecyclerView mRecyStock;
    private View contentView;
    private int expiryDate,stockNameID;

    @Override
    protected int getLayoutId() {
        return R.layout.act_take_stock;
    }

    @Override
    protected void initView() {
        contentView = getLayoutInflater().inflate(R.layout.content_allpro_dta, null);
        mSwipeLayout = contentView.findViewById(R.id.swipe_layout);
        mRecyStock = contentView.findViewById(R.id.recy_all_pro);
        macAddress = MacUtils.getFormatMacAddr();
        categoryList = new ArrayList<>();
        ManufacturerSelList = new ArrayList<>();
        ModelSelList = new ArrayList<>();
        mTagRealList = new MTagRealList();
        productsPresenter = new ProductsByCategoryPresenter(this, new ProductsByCategoryModel());
        confirmStockPresenter = new ConfirmStockPresenter(this, new ConfirmStockModel());
        mToolbar.setIsShowBac(false);
        mToolbar.setTitle("盘点");
        mData = new ArrayList<>();
        mAdapter = new TakeStockAdapter(mData);
        mRecyStock.setLayoutManager(new RecyclerViewNoBugLinearLayoutManager(context));
        mRecyStock.setAdapter(mAdapter);
        mAdapter.bindToRecyclerView(mRecyStock);
        mAdapter.setEmptyView(R.layout.empty_view);
        typeDtaPresenter = new ProductTypeDtaPresenter(this, new ProductTypeDtaModel());
        SoundPoolUtils.play(context,R.raw.raw_opean,0);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        mDropDownMenu.setFocusableInTouchMode(true);
        mDropDownMenu.requestFocus();
        mDropDownMenu.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                //退出activity前关闭菜单
                if (mDropDownMenu.isShowing()) {
                    mDropDownMenu.closeMenu();
                    return true;
                } else {
                    return false;
                }
            }
            return false;
        });
    }


    @Override
    protected void onScanResult(List<InventoryBuffer.InventoryTagMap> lsTagList) {
        super.onScanResult(lsTagList);

        mTagRealList.clear();
        mTagRealList.addAllData(lsTagList);
        if (commonShowDialog!=null){
            commonShowDialog.setContentHint("已盘点" + mTagRealList.size() + "件");
        }
        List<String> str = new ArrayList();
        for (int i = 0; i < mTagRealList.size(); i++) {
            str.add(mTagRealList.getData().get(i).strEPC.replace(" ", ""));
        }
        confirmStockPresenter.getConfirmStock(MacUtils.getFormatMacAddr(), MyApplication.getUserInfoGlob().getUsercode(), str, type);

    }


    @Override
    public void startstop(boolean start) {
        if (start) {
            showJieSuanDia();
        }
        super.startstop(start);

    }

    @Override
    protected void initData() {
//        typeDtaPresenter.getCategoryList(macAddress, 1);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> CategoryMap = new HashMap<>();
                Map<String,String> ManufacturersMap = new HashMap<>();
                Map<String,String> ModleMap = new HashMap<>();
                List<ProAllEntity> selfProList = DBUtils.getInstance().getProAllDao().getSelfProList();
                for (int i = 0; i < selfProList.size(); i++) {
                    if (!(selfProList.get(i).getCategoryLevel2Name().equals("-")||selfProList.get(i).getCategoryLevel2Name().equals(""))){
                        CategoryMap.put(selfProList.get(i).getCategoryLevel2Name(),selfProList.get(i).getCategoryLevel2());
                    }
                    if (!(selfProList.get(i).getVendorName().equals("-")||selfProList.get(i).getVendorName().equals(""))){
                        ManufacturersMap.put(selfProList.get(i).getVendorName(),selfProList.get(i).getProductVendor());
                    }
                    if (!(selfProList.get(i).getRegularModel().equals("-")||selfProList.get(i).getRegularModel().equals(""))){
                        ModleMap.put(selfProList.get(i).getRegularModel(),selfProList.get(i).getRegularModel());
                    }
                }

                categoryList.add(new CategoryListEntity("全部",""));
                for (String key:CategoryMap.keySet()) {
                    CategoryListEntity categoryListEntity = new CategoryListEntity();
                    categoryListEntity.setLabel(key);
                    categoryListEntity.setValue(CategoryMap.get(key));
                    categoryList.add(categoryListEntity);
                }

                ManufacturerSelList.add(new CategoryListEntity("全部",""));
                for (String key:ManufacturersMap.keySet()) {
                    CategoryListEntity categoryListEntity = new CategoryListEntity();
                    categoryListEntity.setLabel(key);
                    categoryListEntity.setValue(ManufacturersMap.get(key));
                    ManufacturerSelList.add(categoryListEntity);
                }

                ModelSelList.add(new CategoryListEntity("全部",""));
                for (String key:ModleMap.keySet()) {
                    CategoryListEntity categoryListEntity = new CategoryListEntity();
                    categoryListEntity.setLabel(key);
                    categoryListEntity.setValue(ModleMap.get(key));
                    ModelSelList.add(categoryListEntity);
                }
                List<String> categoryStrings = new ArrayList<>();
                for (CategoryListEntity categoryListEntity : categoryList) {
                    categoryStrings.add(categoryListEntity.getLabel());
                }
                selectTypeOne = categoryStrings.toArray(new String[categoryStrings.size()]);

                List<String> ManufacStrings = new ArrayList<>();
                for (CategoryListEntity categoryListEntity : ManufacturerSelList) {
                    ManufacStrings.add(categoryListEntity.getLabel());
                }
                selectTypeThree = ManufacStrings.toArray(new String[ManufacStrings.size()]);
                List<String> ModelStrings = new ArrayList<>();
                for (CategoryListEntity categoryListEntity : ModelSelList) {
                    ModelStrings.add(categoryListEntity.getLabel());
                }
                selectTypeTwo = ModelStrings.toArray(new String[ModelStrings.size()]);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mDropDownMenu.setDropDownMenu(Arrays.asList(headers), initViewData(), contentView);

                    }
                });
                opeanDoor();

            }
        }).start();

    }

    @Override
    protected void bindListener() {
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent  = new Intent(context,ProDetailActivity.class);
                intent.putExtra("manufacturer", mAdapter.getData().get(position).getProductVendor());
                intent.putExtra("productNo",mAdapter.getData().get(position).getProductNo());
                intent.putExtra("model",mAdapter.getData().get(position).getProductModel());
                intent.putExtra("stockNameID",stockNameID);
                intent.putExtra("productName",mAdapter.getData().get(position).getProductName());
                intent.putExtra("type", 1);
                startActivity(intent);

            }
        });


        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isLoadMore = false;
                pageNum = 1;//设为默认加载第一页
                mData.clear();
                productsPresenter.getProDta(macAddress, categoryValue, stockName, model, manufacturer, expiryDate, 1, pageSize, pageNum);
            }
        });

//        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
//            @Override
//            public void onLoadMoreRequested() {
//                isLoadMore = true;
//                productsPresenter.getProDta(macAddress, categoryValue, stockName, model, manufacturer, expiryDate, 1, pageSize, pageNum);
//
//            }
//        });
        mSwipeLayout.setRefreshing(true);
        mSwipeLayout.post(() -> {
            productsPresenter.getProDta(macAddress, categoryValue, stockName, model, manufacturer, expiryDate, 1, pageSize, pageNum);
        });

        //该监听回调只监听默认类型，如果是自定义view请自行设置，参照demo
        mDropDownMenu.addMenuSelectListener((index, pos, clickstr) -> {
            //index:点击的tab索引，pos：单项菜单中点击的位置索引，clickstr：点击位置的字符串
            LogUtil.e(TAG, "===index==" + index + "pos====" + pos);
            if (index == 0) {
                categoryValue = categoryList.get(pos).getValue();
                if (pos == 0) {
                    mDropDownMenu.setTabText(0, "产品类别");
                }
            } else if (index == 1) {
                model = ModelSelList.get(pos).getValue();
                if (pos == 0) {
                    mDropDownMenu.setTabText(1, "产品规格");
                }
            } else {
                manufacturer = ManufacturerSelList.get(pos).getValue();
                if (pos == 0) {
                    mDropDownMenu.setTabText(2, "生产厂家");
                }
            }
            //网络请求
            isLoadMore = false;
            pageNum = 1;//设为默认加载第一页
            mData.clear();
            productsPresenter.getProDta(macAddress, categoryValue, stockName, model, manufacturer, expiryDate, 1, pageSize, pageNum);

        });
    }

    @Override
    protected void afterRequestPermission(int requestCode, boolean isAllGranted) {

    }


    @Override
    public void OnGetConfirmStockSuccess(ResponseBean responseBean) {
        if (commonShowDialog != null) {
            commonShowDialog.dismiss();
            commonShowDialog.closeLoding();
        }
        Intent intent = new Intent(context, ConfirmStockActivity.class);
        ConfirmStockEntity StockInfo = (ConfirmStockEntity) responseBean.pullData();
        intent.putExtra("StockInfo", StockInfo);
        startActivity(intent);
        finish();

    }

    @Override
    public void onGetCategoryListSuccess(ResponseBean responseBean) {
        categoryList = (List<CategoryListEntity>) responseBean.pullData();
        if (categoryList == null)
            return;
        List<String> strings = new ArrayList<>();
        for (CategoryListEntity categoryListEntity : categoryList) {
            strings.add(categoryListEntity.getLabel());
        }
        selectTypeOne = strings.toArray(new String[strings.size()]);
        typeDtaPresenter.getManufacturerSel(macAddress, 1);
    }

    @Override
    public void onGetStockSelSuccess(ResponseBean responseBean) {

    }

    @Override
    public void onManufacturerSelSuccess(ResponseBean responseBean) {
        ManufacturerSelList = (List<CategoryListEntity>) responseBean.pullData();
        if (ManufacturerSelList == null)
            return;
        List<String> strings = new ArrayList<>();
        for (CategoryListEntity categoryListEntity : ManufacturerSelList) {
            strings.add(categoryListEntity.getLabel());
        }
        selectTypeThree = strings.toArray(new String[strings.size()]);
        typeDtaPresenter.getModelSel(macAddress, 1);
    }

    @Override
    public void onModelSelSuccess(ResponseBean responseBean) {
        ModelSelList = (List<CategoryListEntity>) responseBean.pullData();
        if (ModelSelList == null)
            return;
        List<String> strings = new ArrayList<>();
        for (CategoryListEntity categoryListEntity : ModelSelList) {
            strings.add(categoryListEntity.getLabel());
        }
        selectTypeTwo = strings.toArray(new String[strings.size()]);
        mDropDownMenu.setDropDownMenu(Arrays.asList(headers), initViewData(), contentView);

    }

    @Override
    public void onGetProDtaSuccess(ResponseBean responseBean) {
        mSwipeLayout.setRefreshing(false);//完成刷新
        responseBean.setClass(NewTakeStockEntity.class);
        NewTakeStockEntity stockEntity = (NewTakeStockEntity) responseBean.pullData();
        if (stockEntity == null)
            return;
        mTvAllNum.setText(stockEntity.getStock());
        mData = stockEntity.getList();
        if (isLoadMore) {
            mAdapter.loadMoreComplete();//网络请求成功的话调用loadMoreComplete()
        }
        if (mData != null && mData.size() > 0) {//有了请求数据
            if (isLoadMore) {//为true时，是加载更多获取的数据
                mAdapter.addData(mData);//加载更多的数据，add进去
            } else {
                mAdapter.setNewData(mData);//进入或者上拉加载的数据(page=1),setnewdata
            }
            if (mData.size() == pageSize) {//获取的数据未10条时，说明还有下一页，page加1，以备下次请求
                pageNum++;
                mAdapter.setEnableLoadMore(true);//允许加载更多
            } else {
                mAdapter.loadMoreEnd(true);//若这次获得的数据没有10条，说明全部加载完毕。
            }

        } else {
            if (pageNum == 1) {
                //数据得清空才会显示空布局
                mAdapter.getData().clear();
                mAdapter.notifyDataSetChanged();
            }
            mAdapter.loadMoreEnd(true);//若这次获得的数据没有10条，说明全部加载完毕。

        }

    }

    @Override
    public void onError(String msg) {
        ToastUtils.showText(msg);
        if (commonShowDialog != null) {
            commonShowDialog.dismiss();
            commonShowDialog.closeLoding();
        }

        finish();

    }

    //结算中弹框
    private void showJieSuanDia() {
        commonShowDialog = new CommonShowDialog(context);
        commonShowDialog.setContent("正在结算中");
        commonShowDialog.setContentHint("请稍候...");
        commonShowDialog.setImgShow(R.mipmap.icon_jiesuan);
        commonShowDialog.show();
        commonShowDialog.setCancelable(false);
        commonShowDialog.showLoding();
    }


    /**
     * 设置类型和数据源：
     * DropDownMenu.KEY对应类型（DropDownMenu中的常量，参考上述核心源码）
     * DropDownMenu.VALUE对应数据源：key不是TYPE_CUSTOM则传递string[],key是TYPE_CUSTOM类型则传递对应view
     */
    private List<HashMap<String, Object>> initViewData() {
        List<HashMap<String, Object>> viewDatas = new ArrayList<>();
        HashMap<String, Object> map;
        for (int i = 0; i < headers.length; i++) {
            map = new HashMap<String, Object>();
            map.put(DropDownMenu.KEY, types[i]);
            if (i == 0) {
                map.put(DropDownMenu.VALUE, selectTypeOne);
//                map.put(DropDownMenu.SELECT_POSITION, 1);

            } else if (i == 1) {
                map.put(DropDownMenu.VALUE, selectTypeTwo);
//                map.put(DropDownMenu.SELECT_POSITION, 0);

            } else if (i == 2) {
                map.put(DropDownMenu.VALUE, selectTypeThree);
//                map.put(DropDownMenu.SELECT_POSITION,2);

            }
            viewDatas.add(map);
        }
        return viewDatas;
    }


    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (isCloseDoor) {
                finish();
            } else {
                ToastUtils.showText(this, "请先关紧柜门！");
            }
            return true;
        } else {
            return super.dispatchKeyEvent(event);
        }
    }



    @Override
    protected void onDestroy() {
        if (commonShowDialog != null) {
            commonShowDialog.dismiss();
            commonShowDialog.closeLoding();
        }
        super.onDestroy();
    }


}